<template>
  <common-edit-dialog
    :title="dialogTitle"
    :visible.sync="dialogShow"
    @cancel="dialogShow = false"
    @submit="submitForm"
    :button-loading="isPersistenceLoading"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.native.prevent
    >
      <el-form-item label="针对用户" prop="userCode">
        <common-input
          v-model="form.userCode"
          placeholder="请输入名称"
          disabled
        />
      </el-form-item>
      <!-- <el-form-item
        label="允许访问IP"
        prop="ipAddress"
        v-if="form.userVisitRuleId"
        :rules="{ required: true, message: '请填写访问ip', trigger: 'blur' }"
      >
        <div style="display: flex;">
          <common-input v-model="form.ipAddress" placeholder="请输入IP地址" /><span style="margin-left: 15px; margin-right: 15px;"> ~ </span>
          <common-input v-model="form.ipAddress2" placeholder="范围（选填）" />
        </div>
      </el-form-item> -->

      <div style="display: flex" v-if="form.userVisitRuleId">
        <el-form-item
          class="ipAddrItem1"
          label="允许访问IP"
          prop="ipAddress1"
          :rules="{ required: true, message: '请填写访问ip', trigger: 'blur' }"
        >
          <common-input v-model="form.ipAddress1" :verify="false" placeholder="支持IPV4/IPV6格式" />
        </el-form-item>
        <span style="margin-left: 15px; margin-right: 15px; line-height: 33px">
          ~
        </span>
        <el-form-item prop="ipAddress2" class="ipAddrItem2">
          <common-input v-model="form.ipAddress2" placeholder="范围（选填）" />
        </el-form-item>
      </div>

      <!--      <el-form-item-->
      <!--        class="leaderDep"-->
      <!--        v-for="(item, index) in form.depList"-->
      <!--        :label="'参与部门' + (index + 1)"-->
      <!--        :key="item.key"-->
      <!--        :prop="'depList.' + index + '.value'"-->
      <!--        :rules="{-->
      <!--                                required: true, message: '请选择参与部门', trigger: 'change'-->
      <!--                            }"-->
      <!--      >-->
      <!--        <div class="leadDepItem">-->
      <!--          <div class="depItem">-->
      <!--            <el-cascader-->
      <!--              :options="leadDepList"-->
      <!--              v-model="item.value"-->
      <!--              placeholder="请选择部门"-->
      <!--              @change="handleChangeDep(item,index)"-->
      <!--              :props="props"-->
      <!--              clearable-->
      <!--              :show-all-levels="false"-->
      <!--              change-on-select>-->
      <!--            </el-cascader>-->
      <!--          </div>-->
      <!--          <div class="userItem">-->
      <!--            <el-select v-model="item.userId" placeholder="请选择人员" filterable clearable>-->
      <!--              <el-option-->
      <!--                v-for="items in item.userLists"-->
      <!--                :key="items.id"-->
      <!--                :label="items.username"-->
      <!--                :value="items.id">-->
      <!--              </el-option>-->
      <!--            </el-select>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--        <el-button @click.prevent="remove(item)" type="text" style="margin-left: 10px;color: #F56C6C;" >删除</el-button>-->
      <!--      </el-form-item>-->

      <el-form-item
        v-for="(item, index) in form.ipAddressList"
        :label="'允许访问IP'"
        :key="index"
        :prop="'ipAddressList.' + index + '.value'"
        :rules="rules.IP"
      >
        <div style="display: flex">
          <common-input v-model="item.value" @input="newinput" :verify="false" placeholder="支持IPV4/IPV6格式"></common-input
          ><span style="margin-left: 15px; margin-right: 15px"> ~ </span>
          <common-input
            v-model="item.value2"
            placeholder="范围（选填）"
            @input="newinput"
          ></common-input>
          <el-button
            style="font-size: 12px; margin-left: 7px"
            type="danger"
            clearable
            plain
            v-if="form.ipAddressList.length > 1"
            @click.prevent="removeDomain(item)"
            >删除
          </el-button>
          <el-button
            type="primary"
            style="font-size: 12px; margin-left: 7px"
            plain
            v-if="index === 0"
            @click.prevent="addDomain()"
            >新增
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </common-edit-dialog>
</template>

<script>
import {
  visitsourcerule_insertUserVisitRule,
  visitsourcerule_updateUserVisitRule,
} from "@/api/management/configure/index.js";
import { validateIP } from "@/utils/formValidates";

// const validateIP = validateIP

export default {
  components: {},
  props: {},

  data() {
    const checkIP = (rule, value, callback) => {
      let i = parseInt(rule.field.split(".")[1]);
      console.log(this.form.ipAddressList);
      let item = this.form.ipAddressList[i];
      if (!value) {
        callback(new Error("请输入访问IP"));
      } else if (
        this.form.ipAddressList.filter((f) => f.value === item.value).length > 1
      ) {
        callback(new Error("访问IP不能重复"));
      } else {
        callback();
      }
    };
    return {
      isPersistenceLoading: false,
      dialogTitle: "新增访问来源策略", // 标题
      dialogShow: false, // 是否显示
      form: {
        ipAddressList: [{ value: "", value2: "" }],
        ipAddress1: "",
        ipAddress2: "",
        ipAddress: ""
      },
      rules: {
        userCode: [
          {
            required: true,
            message: "请输入针对用户",
            trigger: "blur",
          },
        ],
        IP: [
          { required: true, validator: checkIP, trigger: "blur" },
          {
            required: true,
            message: "请输入正确的IP地址,支持ipv4/ipv6格式",
            validator: validateIP,
            trigger: "blur",
          },
        ],
        // ruleName: [
        // 	{
        // 		required: true,
        // 		message: '请输入策略名称',
        // 		trigger: 'blur',
        // 	},
        // ],
      },
    };
  },
  watch: {},
  computed: {},
  methods: {
    /**
     * 关闭
     */
    close() {
      // this.$refs.form.resetFields();
      this.dialogShow = false;
      this.$emit("refresh");
    },
    /**
     * 显示
     */
    show(data) {
      this.form.ipAddress1="";
      this.form.ipAddress2="";
      this.dialogShow = true;
      console.log(data);
      this.dialogTitle = "编辑";
      /* let dataArr = JSON.parse(JSON.stringify(data));
          let ipAddressList = [];
          if (!dataArr.ipAddressList || dataArr.ipAddressList.length == 0) {
            ipAddressList = [
              {
                value: '',
              },
            ];
          } else {
            for (let index in dataArr.ipAddressList) {
              ipAddressList.push({ value: dataArr.ipAddressList[index] });
            }
          }
          dataArr.ipAddressList = ipAddressList;
          this.form = dataArr; */
      if (data.ipAddress) {
        data.ipAddress1 = data.ipAddress.split("-")[0];
        data.ipAddress2 = data.ipAddress.split("-")[1] || "";
      }
      this.form = data;
    },
    /**
     * 添加
     */
    add(userId, userCode) {
      this.dialogShow = true;
      this.form.userId = userId;
      this.form.userCode = userCode;
      this.form.ipAddressList = [
        {
          value: "",
          value2: "",
        },
      ];
    },
    /**
     * 提交
     */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userVisitRuleId) {
            this.form.ipAddress = this.form.ipAddress2 ? this.form.ipAddress1 + "-" + this.form.ipAddress2 : this.form.ipAddress1;
            if (!this.isPersistenceLoading) {
              this.isPersistenceLoading = true;
              visitsourcerule_updateUserVisitRule(this.form)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage("编辑成功");
                    this.close();
                  } else {
                    this.$GlobalErrorConfirm("编辑失败", res.msg);
                  }
                })
                .finally(() => {
                  this.isPersistenceLoading = false;
                });
            }
          } else {
            let form = JSON.parse(JSON.stringify(this.form));
            let ipAddressList = [];
            for (let index in form.ipAddressList) {
              if (form.ipAddressList[index].value2) {
                ipAddressList.push(
                  form.ipAddressList[index].value +
                    "-" +
                    form.ipAddressList[index].value2
                );
              } else {
                ipAddressList.push(form.ipAddressList[index].value);
              }
            }
            form.ipAddressList = ipAddressList;
            if (!this.isPersistenceLoading) {
              this.isPersistenceLoading = true;
              visitsourcerule_insertUserVisitRule(form)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage("新增成功");
                    this.close();
                  } else {
                    this.$GlobalErrorConfirm("新增失败", res.msg);
                  }
                })
                .finally(() => {
                  this.isPersistenceLoading = false;
                });
            }
          }
        }
      });
    },
    removeDomain(item) {
      var index = this.form.ipAddressList.indexOf(item);
      if (index !== -1) {
        this.form.ipAddressList.splice(index, 1);
      }
    },
    addDomain() {
      this.isShow = false;
      this.form.ipAddressList.push({
        value: "",
        value2: "",
      });
    },
    newinput() {
    },
  },
  created() {},
  mounted() {},
};
</script>
<style lang="scss" scoped>
.ipAddrItem1 {
  width: calc(50% + 100px);
  ::v-deep .el-form-item__content {
    width: calc(100% - 100px) !important;
  }
}

.ipAddrItem2 {
  width: 50%;
  ::v-deep .el-form-item__content {
    width: 100% !important;
    margin-left: 0 !important;
  }
}
</style>
